package com.ruoyi.web.controller.wnjk.app.shop;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.wnjk.domain.po.ShopOrder;
import com.ruoyi.system.wnjk.domain.po.ShopOrderDetail;
import com.ruoyi.system.wnjk.domain.vo.ShopOrderVo;
import com.ruoyi.system.wnjk.service.IShopItemService;
import com.ruoyi.system.wnjk.service.IShopOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app/shop/order")
public class AppShopOrderController extends BaseController {

    @Autowired
    private IShopOrderService shopOrderService;   //订单服务
    @Autowired
    private IShopItemService shopItemService;   //商品服务

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    public TableDataInfo list(ShopOrder shopOrder)
    {
        startPage();
        List<ShopOrderVo> list = shopOrderService.selectShopOrderListByUser(shopOrder);
        return getDataTable(list);
    }

    /**
     * 新增【请填写功能名称】
     */
    @PostMapping
    public AjaxResult add(@RequestBody ShopOrderVo shopOrder) {
        try {
            // 生成订单ID
            Long orderId = IdUtil.getSnowflakeNextId();
            shopOrder.setId(orderId); // 设置订单ID

            // 将订单信息存储到Redis中，设置过期时间为30分钟
            redisTemplate.opsForValue().set(orderId.toString(), shopOrder, 30, TimeUnit.MINUTES);

            return AjaxResult.success("创建订单成功", orderId.toString());
        } catch (Exception e) {
            // 如果扣减库存失败，返回错误信息
            return AjaxResult.error("创建订单失败: " + e.getMessage());
        }
    }


    //查看未支付的订单
    @GetMapping("/order/{orderId}")
    public ResponseEntity<ShopOrderVo> getOrder(@PathVariable String orderId) {

        // 从Redis中获取订单信息
        ShopOrderVo orderRequest = (ShopOrderVo) redisTemplate.opsForValue().get(orderId+"");

        if (orderRequest != null) {
            // 构造返回的订单信息
            ShopOrderVo order = new ShopOrderVo();
            order.setId(Long.parseLong(orderId));
            order.setTotalFee(orderRequest.getTotalFee());
            order.setPaymentType(orderRequest.getPaymentType());
            order.setUserId(orderRequest.getUserId());
            order.setShopAddressId(orderRequest.getShopAddressId());

            return ResponseEntity.ok(order);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    /**
     * 取消订单并回滚库存
     */
    @PostMapping("/cancel/{orderId}")
    public AjaxResult cancelOrder(@PathVariable String orderId) {
        try {
            // 从Redis中获取订单信息
            ShopOrderVo orderRequest = (ShopOrderVo) redisTemplate.opsForValue().get(orderId);
            if (orderRequest == null) {
                return AjaxResult.error("订单不存在或已过期");
            }

            // 回滚库存
            List<ShopOrderDetail> orderDetails = orderRequest.getShopOrderDetailList();
            for (ShopOrderDetail detail : orderDetails) {
                Long itemId = detail.getItemId(); // 商品ID
                Long quantity = detail.getNum(); // 购买数量
                // 调用商品服务，增加库存
                shopItemService.increaseStock(itemId, quantity);
            }

            // 从Redis中移除订单
            redisTemplate.delete(orderId);

            return AjaxResult.success("订单取消成功，库存已回滚");
        } catch (Exception e) {
            return AjaxResult.error("取消订单失败: " + e.getMessage());
        }
    }

//    @Transactional(rollbackFor = Exception.class)
//    public void createOrder(Long orderId , ShopOrderVo shopOrder) {
//        // 扣减库存（取消）---------用户点击支付时在扣除库存
//        List<ShopOrderDetail> orderDetails = shopOrder.getShopOrderDetailList();
//        for (ShopOrderDetail detail : orderDetails) {
//            Long itemId = detail.getItemId(); // 商品ID
//            Long quantity = detail.getNum(); // 购买数量
//            // 调用商品服务，扣减库存
//            shopItemService.reduceStock(itemId, quantity);
//        }
//        // 将订单信息存储到Redis中，设置过期时间为30分钟
//        redisTemplate.opsForValue().set(orderId.toString(), shopOrder, 30, TimeUnit.MINUTES);
//    }

}
